package com.aaa.service.impl;


import com.aaa.config.ThreadExecutorConfig;
import com.aaa.data.BookCatalogueDB;
import com.aaa.data.BookChapter;
import com.aaa.data.BookList;
import com.aaa.data.DownloadBook;
import com.aaa.dto.BookCatalogueDto;
import com.aaa.entity.Book;
import com.aaa.entity.FileBook;
import com.aaa.service.BookService;
import com.aaa.util.Download;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;

import static com.aaa.util.Download.download;


/**
 * @author sym
 * @version 1.0
 * @Title: 书籍操作
 * @date 2020/7/24 15:54
 */
@Service
public class BookServiceImpl implements BookService {
    @Override
    public List<BookCatalogueDto> getBookCatalogue(String bookCod, HttpServletRequest request) {
        HttpSession session = request.getSession();
        ExecutorService executorService = ThreadExecutorConfig.testFxbDrawExecutor();
        String dataSource = null;
        try {
            dataSource = session.getAttribute("DATA_SOURCE").toString();
        } catch (NullPointerException e) {
            dataSource = "biquge5200";

        }
        List<BookCatalogueDto> bookCatalogues = BookCatalogueDB.setDataSource(dataSource, bookCod, executorService);
        return bookCatalogues;
    }

    @Override
    public void replaceBackgroup(String file) {
        File file1 = new File("static\\img\\backgroup.jpg");
        if (!file1.exists() || file1.delete()) {
            try {
                FileInputStream input  = new FileInputStream(file);
                file1.createNewFile();
                FileOutputStream output = new FileOutputStream("static\\img\\backgroup.jpg");
                int in  = input.read();

                while(in!=-1){
                    output.write(in);
                    in = input.read();
                }
            } catch (Exception e) {
                e.printStackTrace();
                // TODO: handle exception			e.printStackTrace();
            }
        } ;

    }

    @Override
    public void downloadBook(String bookCod, String bookName, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        HttpSession session = request.getSession();
        ExecutorService executorService = ThreadExecutorConfig.testFxbDrawExecutor();
        String dataSource = null;
        try {
            dataSource = session.getAttribute("DATA_SOURCE").toString();
        } catch (NullPointerException e) {
            dataSource = "biquge5200";
        }
        DownloadBook.setDataSource(bookCod, bookName, dataSource, request, this, executorService);
    }


    @Override
    public BookCatalogueDto getBookChapter(String bookCod, String chapterCod, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String dataSource = null;
        try {
            dataSource = session.getAttribute("DATA_SOURCE").toString();
        } catch (NullPointerException e) {
            dataSource = "biquge5200";
        }
        BookCatalogueDto bookCatalogueDto = BookChapter.setDataSource(dataSource, bookCod, chapterCod);
        return bookCatalogueDto;
    }

    @Override
    public List<Book> getBookList(String key, String dataSource, HttpServletRequest request) {
        ExecutorService executorService = ThreadExecutorConfig.testFxbDrawExecutor();

        HttpSession session = request.getSession();
        if (dataSource == null) {
            dataSource = "biquge5200";
        } else {
            session.removeAttribute("DATA_SOURCE");
        }
        session.setAttribute("DATA_SOURCE", dataSource);
        List<Book> books = BookList.setDataSource(session.getAttribute("DATA_SOURCE").toString(), key, executorService);
        return books;
    }

    @Override
    public List<FileBook> getBookFile(Integer page) {
        int num = page * 5;
        File file = new File("/usr/local/webapps/file");
        File[] files = file.listFiles();
        List<FileBook> fileBooks = new ArrayList<>(files.length);
        if (files == null) {
            return null;
        }
        List<File> list = new ArrayList<>(Arrays.asList(files));
        int ceil = (int) Math.ceil((double) list.size() / 5);
        list = list.subList(num - 5, Math.min(num, list.size()));
        for (int i = 0; i < list.size(); i++) {
            FileBook fileBook = new FileBook();
            fileBook.setBookName(list.get(i).getName());
            fileBook.setFileSize(getFileSize(list.get(i)));
            fileBook.setPageSize(ceil);
            fileBooks.add(fileBook);
        }
        return fileBooks;
    }

    public static String getFileSize(File file) {
        String size = "";
        if (file.exists() && file.isFile()) {
            long fileS = file.length();
            DecimalFormat df = new DecimalFormat("#.00");
            if (fileS < 1024) {
                size = df.format((double) fileS) + "BT";
            } else if (fileS < 1048576) {
                size = df.format((double) fileS / 1024) + "KB";
            } else if (fileS < 1073741824) {
                size = df.format((double) fileS / 1048576) + "MB";
            } else {
                size = df.format((double) fileS / 1073741824) + "GB";
            }
        } else if (file.exists() && file.isDirectory()) {
            size = "";
        } else {
            size = "0BT";
        }
        return size;
    }

}
